package com.xggstudio.crm.ui.mvp.v;
import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.xggstudio.crm.R;
import com.xggstudio.crm.base.BaseActivity;
import com.xggstudio.crm.base.Constant;
import com.xggstudio.crm.tools.JsonFileReader;
import com.xggstudio.crm.ui.mvp.m.ProvinceBean;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class EditActivity extends BaseActivity implements View.OnClickListener {

    private Toolbar toolbar;

    private TextView bartext;

    private EditText text;

    private TextView text1;

    private int resultCode;

    private String title;

    @Override
    protected int getLayout() {
        return R.layout.view_edit;
    }

    @Override
    protected void init(Bundle savedInstanceState) {

        initView();
        getIntentData();
    }

    @SuppressLint("RestrictedApi")
    private void initView(){

        text1 = (TextView) $(R.id.text1);
        text = (EditText) $(R.id.text);
        bartext = (TextView) $(R.id.bar_text);
        toolbar = (Toolbar) $(R.id.toolbar);

        toolbar.setTitle("");
        bartext.setText("");

        setSupportActionBar(toolbar);
        getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        text1.setOnClickListener(this);

        initPickerView();
    }

    private void getIntentData(){

        if(getIntent() != null){
            title = getIntent().getStringExtra(Constant.CUS_NAME);
            String content = getIntent().getStringExtra(Constant.CUS_CONTENT);

            bartext.setText(title);

            resultCode = getIntent().getIntExtra(Constant.CUS_RESULS,0);

            if(content != null){
                int length = content.length();
                text.setText(content);
                text.setSelection(length);
                text1.setText(content);
            }

            if(!isEdit(title)){
                text1.setVisibility(View.VISIBLE);
                text.setVisibility(View.GONE);
            }else{
                text1.setVisibility(View.GONE);
                text.setVisibility(View.VISIBLE);
            }

            if(title.equals("地区")){
                setSelectOptions(content);
            }

        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_add_cus,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()){
            case R.id.menu_add:
                saveFinish();
                break;
            case android.R.id.home:
                finish();
                break;
        }

        return super.onOptionsItemSelected(item);
    }

    private void saveFinish(){

        String s = text.getText().toString();

        if(TextUtils.isEmpty(s)){

            return;
        }

        Intent intent = new Intent();
        intent.putExtra(Constant.CUS_NAME,title);
        intent.putExtra(Constant.CUS_CONTENT,s);

        setResult(resultCode,intent);

        finish();
    }

    private boolean isEdit(String name){
        switch (name){
            case "性别":
                return false;
            case "客户来源":
                return false;
            case "客户类型":
                return false;
            case "状态":
                return false;
            case "下次回访":
                return false;
            case "地区":
                return false;
        }
        return true;
    }

    @SuppressLint("NewApi")
    @Override
    public void onClick(View view) {

        switch (title){
            case "性别":
                showSex();
                break;
            case "客户来源":
                showCusCome();
                break;
            case "客户类型":
                showCusType();
                break;
            case "状态":
                showCusStatus();
                break;
            case "下次回访":
                showDate();
                break;
            case "地区":
                pvOptions.show();
                break;
        }

    }


    private void showSex(){

        final String[] array = new String[]{"男","女"};

        AlertDialog.Builder alert = new AlertDialog.Builder(this);
        alert.setTitle("选择");
        alert.setItems(array, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                text1.setText(array[i]);
                text.setText(array[i]);
            }
        });
        alert.create().show();

    }

    private void showCusCome(){

        final String[] array = new String[]{"线上","线下"};

        AlertDialog.Builder alert = new AlertDialog.Builder(this);
        alert.setTitle("选择");
        alert.setItems(array, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                text1.setText(array[i]);
                text.setText(array[i]);
            }
        });
        alert.create().show();

    }

    private void showCusType(){
        final String[] array = new String[]{"留学","移民","房产","龟龟伙伴"};

        AlertDialog.Builder alert = new AlertDialog.Builder(this);
        alert.setTitle("选择");
        alert.setItems(array, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                text1.setText(array[i]);
                text.setText(array[i]);
            }
        });
        alert.create().show();
    }

    private void showCusStatus(){


        final String[] array = new String[]{"跟进中","无需跟进"};

        AlertDialog.Builder alert = new AlertDialog.Builder(this);
        alert.setTitle("选择");
        alert.setItems(array, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                text1.setText(array[i]);
                text.setText(array[i]);
            }
        });
        alert.create().show();

    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private void showDate(){

        Calendar calendar = Calendar.getInstance();


        DatePickerDialog dialog = new DatePickerDialog(EditActivity.this,DatePickerDialog.THEME_DEVICE_DEFAULT_LIGHT, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int year, int month, int day) {

                String date = year + "-"+ (month + 1) + "-" + day;

                text.setText(date);
                text1.setText(date);

            }
        },calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));

        dialog.show();
    }


    OptionsPickerView pvOptions;
    //  省份
    ArrayList<String> provinceBeanList = new ArrayList<>();
    //  城市
    ArrayList<String> cities;
    ArrayList<List<String>> cityList = new ArrayList<>();
    //  区/县
    ArrayList<String> district;
    ArrayList<List<String>> districts;
    ArrayList<List<List<String>>> districtList = new ArrayList<>();

    private void initPickerView(){

        //  创建选项选择器
        pvOptions = new OptionsPickerView(this);

        //  获取json数据
        String province_data_json = JsonFileReader.getJson(this, "province_data.json");
        //  解析json数据
        parseJson(province_data_json);

        //  设置三级联动效果
        pvOptions.setPicker(provinceBeanList, cityList, districtList, true);


        //  设置选择的三级单位
        //pvOptions.setLabels("省", "市", "区");
        //pvOptions.setTitle("选择城市");

        //  设置是否循环滚动
        pvOptions.setCyclic(false, false, false);


        // 设置默认选中的三级项目
        pvOptions.setSelectOptions(0, 0, 0);
        //  监听确定选择按钮
        pvOptions.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                //返回的分别是三个级别的选中位置
                String city = provinceBeanList.get(options1);
                String address;
                //  如果是直辖市或者特别行政区只设置市和区/县
             /*   if ("北京市".equals(city) || "上海市".equals(city) || "天津市".equals(city) || "重庆市".equals(city) || "澳门".equals(city) || "香港".equals(city)) {
                    address = provinceBeanList.get(options1)
                            + "-" + districtList.get(options1).get(option2).get(options3);
                } else {*/
                    address = provinceBeanList.get(options1)
                            + "-" + cityList.get(options1).get(option2)
                            + "-" + districtList.get(options1).get(option2).get(options3);
               /* }*/
                //mTextViewAddress.setText(address);
                text.setText(address);
                text1.setText(address);
            }
        });

    }

    //  解析json填充集合
    public void parseJson(String str) {
        try {
            //  获取json中的数组
            JSONArray jsonArray = new JSONArray(str);
            //  遍历数据组
            for (int i = 0; i < jsonArray.length(); i++) {
                //  获取省份的对象
                JSONObject provinceObject = jsonArray.optJSONObject(i);
                //  获取省份名称放入集合
                String provinceName = provinceObject.getString("name");

                provinceBeanList.add(provinceName);
                //  获取城市数组
                JSONArray cityArray = provinceObject.optJSONArray("city");
                cities = new ArrayList<>();//   声明存放城市的集合
                districts = new ArrayList<>();//声明存放区县集合的集合
                //  遍历城市数组
                for (int j = 0; j < cityArray.length(); j++) {
                    //  获取城市对象
                    JSONObject cityObject = cityArray.optJSONObject(j);
                    //  将城市放入集合
                    String cityName = cityObject.optString("name");
                    cities.add(cityName);
                    district = new ArrayList<>();// 声明存放区县的集合
                    //  获取区县的数组
                    JSONArray areaArray = cityObject.optJSONArray("area");
                    //  遍历区县数组，获取到区县名称并放入集合
                    for (int k = 0; k < areaArray.length(); k++) {
                        String areaName = areaArray.getString(k);
                        district.add(areaName);
                    }
                    //  将区县的集合放入集合
                    districts.add(district);
                }
                //  将存放区县集合的集合放入集合
                districtList.add(districts);
                //  将存放城市的集合放入集合
                cityList.add(cities);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void setSelectOptions(String address){

        if(address == null) return;
        if(TextUtils.isEmpty(address))return;

        String[] names = address.split("-");
        int p = getitemIndex(provinceBeanList,names[0]);
        int c = getitemIndex(cityList.get(p),names[1]);
        int d = getitemIndex(districtList.get(p).get(c),names[2]);

        pvOptions.setSelectOptions(p, c, d);
    }

    public int getitemIndex(List<String> data,String name){

        if(data == null) return 0;
        if(name.equals("null")) return 0;

        for (int i = 0; i < data.size(); i++) {
            if(data.get(i).equals(name)){
                return i;
            }

        }
        return 0;
    }

    // 返回参数

}
